package com.xuan.chatroom.service;


import com.xuan.chatroom.mapper.MessageMapper;
import com.xuan.chatroom.mapper.MessageSessionMapper;
import com.xuan.chatroom.model.Friend;
import com.xuan.chatroom.model.MessageSession;
import com.xuan.chatroom.model.MessageSessionUserItem;
import com.xuan.chatroom.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class MessageSessionService {
    @Resource
    private MessageSessionMapper sessionMapper;
    @Resource
    private MessageMapper messageMapper;

    public List<MessageSession> getMessageSessionList(int userId) {
        List<MessageSession> messageSessionList = new ArrayList<>();
        // 1. 根据 userId 获取当前所有存在的 会话id
        List<Integer> sessionIdList = sessionMapper.queryAllSessionIdByUserId(userId);
        if (sessionIdList == null) {
            return messageSessionList;
        }

        for (Integer sessionId : sessionIdList) {
            // 2. 根据 sessionId 获取每个会话中存在的 friends
            MessageSession messageSession = new MessageSession();
            //  !!!!!!!!!!!!!!!!!!前面没有设置sessionId 导致前端设置标签属性为空,进而导致点击会话时发生的 sessionId为null
            messageSession.setSessionId(sessionId);
            List<Friend> friendList = sessionMapper.queryFriendsBySessionId(sessionId, userId);
            messageSession.setFriends(friendList);

            // 3. 遍历每个会话id,查询每个会话的最后一条消息
            //  lastMessage 可能不存在,因为刚创建的会话没有消息记录
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            if (lastMessage == null) {
                messageSession.setLastMessage("");
            } else {
                messageSession.setLastMessage(lastMessage);
            }
            messageSessionList.add(messageSession);
        }

        return messageSessionList;
    }


    @Transactional
    public Result addSession(Integer toUserId, int userId) {
        MessageSession messageSession = null;
        // 1. 往 message_session 中新增会话记录
        int res = sessionMapper.addMessageSession(messageSession = new MessageSession());
        if (res == 0) return Result.fail("新增会话失败", null);

        // 2. 往 会话-用户 关系表中新增记录
        Integer sessionId = messageSession.getSessionId();
        sessionMapper.addMessageSessionUser(new MessageSessionUserItem(sessionId, toUserId));
        sessionMapper.addMessageSessionUser(new MessageSessionUserItem(sessionId, userId));

        Map<String, Integer> map = new HashMap<>();
        map.put("sessionId", sessionId);
        log.info("新增会话成功!");
        return Result.success(map);
    }
}
